<template>
  <view class="payment-page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="nav-left" @click="onPayBack()">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-title">安全支付</view>
    </view>

    <!-- 支付金额 -->
    <view class="amount-section">
      <text class="amount">¥{{ totalPrice }}</text>
      <text class="countdown">剩余时间：{{ countdownTime }}</text>
    </view>

    <!-- 支付方式列表 -->
    <view class="payment-methods">
      <text class="section-title">请选择支付方式</text>
      <view
        class="method-item"
        v-for="method in paymentMethods"
        :key="method.id"
        @click="selectPaymentMethod(method.id)"
      >
        <view class="method-left">
          <image class="method-icon" :src="method.icon" mode="aspectFit" />
          <text class="method-name">{{ method.name }}</text>
        </view>
        <radio :checked="selectedMethod === method.id" color="#007aff" />
      </view>
    </view>

    <!-- 底部支付按钮 -->
    <view class="bottom-bar">
      <view class="price-info">
        <text>实付金额</text>
        <text class="final-price">¥{{ totalPrice }}</text>
      </view>
      <u-button class="pay-btn" @click="handlePay()">立即支付</u-button>
    </view>

    <!-- 支付弹窗 -->
    <u-modal
      :show="showPayModal"
      confirmt-text="支付"
      cancel-text="返回"
      :show-cancel-button="true"
      :show-confirm-button="true"
      @confirm="doPay"
      @cancel="onPayBack"
      width="600rpx"
      ><view style="text-align: center; padding: 30rpx 0">
        <text>{{ selectedMethodObj.name }}</text>
        <view style="height: 16rpx"></view>
        <text>¥{{ totalPrice }}</text>
      </view>
    </u-modal>

    <!-- 放弃支付确认弹窗 -->
    <u-modal
      :show="showGiveUpModal"
      :show-cancel-button="true"
      :show-confirm-button="true"
      cancel-text="放弃支付"
      confirm-text="继续支付"
      @cancel="giveUpPay"
      @confirm="continuePay"
      width="600rpx"
    >
      <view style="text-align: center; padding: 30rpx 0">
        <text>放弃本次支付吗？</text>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { pay, update, orderDetail } from "@/api/system/order.js";

export default {
  data() {
    return {
      orderId: "",
      orderNumber: "",
      totalPrice: "",
      countdownTime: "",
      selectedMethod: "alipay",
      paymentMethods: [
        {
          id: "alipay",
          name: "支付宝支付",
          icon: "/static/images/alipay.png",
        },
        {
          id: "wechat",
          name: "微信支付",
          icon: "/static/images/wechat.png",
        },
        {
          id: "bank",
          name: "银行支付",
          icon: "/static/images/bank.png",
        },
        {
          id: "union",
          name: "招商银行一网通",
          icon: "/static/images/union.png",
        },
        {
          id: "points",
          name: "小数金币",
          icon: "/static/images/points.png",
        },
      ],
      showPayModal: false, //显示支付弹窗
      showGiveUpModal: false, //显示放弃订单弹窗
      currentOrder: null,
      isFromOrderList: false,
    };
  },
  computed: {
    selectedMethodObj() {
      return (
        this.paymentMethods.find((m) => m.id === this.selectedMethod) || {}
      );
    },
  },
  methods: {
    // 返回
    goBack() {
      uni.navigateBack();
    },
    // 获取传递过来的参数
    async onLoad(options) {
      if (options.orderId) {
        // 订单列表来的
        this.isFromOrderList = true;
        this.orderId = options.orderId;
        // 请求后端获取订单详情
        try {
          const res = await orderDetail(this.orderId);
          if (res.code === 200 && res.data) {
            this.currentOrder = res.data;
            this.totalPrice = res.data.totalAmount || res.data.totalPrice;
            this.orderNumber = res.data.orderNumber;
          } else {
            uni.showToast({ title: res.msg || "订单获取失败", icon: "none" });
          }
        } catch (e) {
          uni.showToast({ title: "网络异常", icon: "none" });
        }
      } else if (options.orderNumber) {
        // 预定页来的
        this.isFromOrderList = false;
        this.orderNumber = options.orderNumber;
        const unpaidOrders = uni.getStorageSync("unpaidOrders") || [];
        this.currentOrder = unpaidOrders.find(
          (order) => order.orderNumber === this.orderNumber
        );
        if (!this.currentOrder) {
          uni.showToast({ title: "订单不存在", icon: "none" });
          return;
        }
        this.totalPrice =
          this.currentOrder.totalAmount || this.currentOrder.totalPrice;
        this.orderId = this.currentOrder.orderId || "";
      }
    },
    // 选择支付方式
    selectPaymentMethod(methodId) {
      this.selectedMethod = methodId;
    },
    // 支付弹窗
    handlePay() {
      this.showPayModal = true;
    },
    //取消支付
    onPayBack() {
      this.showPayModal = false;
      this.showGiveUpModal = true;
    },
    // 放弃支付
    giveUpPay() {
      this.showGiveUpModal = false;
      // 直接跳转到订单详情页
      if (this.orderId) {
        uni.redirectTo({
          url: `/pages/order/order-detail?id=${this.orderId}`,
        });
      } else {
        uni.showToast({ title: "订单信息缺失", icon: "none" });
      }
    },
    //继续支付
    continuePay() {
      this.showGiveUpModal = false;
      this.showPayModal = true;
    },
    //执行支付逻辑
    doPay() {
      uni.showLoading({
        title: "支付处理中",
      });
      const userId = uni.getStorageSync("userId");
      if (this.orderId) {
        // 订单已存在，修改状态
        const paymentRequest = {
          orderId: this.orderId,
          status: 1,
        };
        update(paymentRequest)
          .then((res) => {
            uni.hideLoading();
            if (res.code === 200) {
              uni.showToast({ title: "支付成功", icon: "success" });
              // 清除本地该订单
              let unpaidOrders = uni.getStorageSync("unpaidOrders") || [];
              unpaidOrders = unpaidOrders.filter(
                (order) => order.orderNumber !== this.orderNumber
              );
              uni.setStorageSync("unpaidOrders", unpaidOrders);
              setTimeout(() => {
                uni.redirectTo({ url: "/pages/pay/payment-success" });
              }, 1500);
            } else {
              uni.showToast({ title: res.msg || "支付失败", icon: "none" });
            }
          })
          .catch(() => {
            uni.hideLoading();
            uni.showToast({ title: "支付异常", icon: "none" });
          });
      } else {
        // 订单不存在，直接新建已支付订单
        const order = this.currentOrder;
        const paymentRequest = {
          userId,
          status: 1,
          homeId: order.homeId,
          roomId: order.roomId,
          checkInDate: order.checkInDate,
          checkOutDate: order.checkOutDate,
          roomCount: order.roomCount,
          guestName: order.guestName,
          guestPhone: order.guestPhone,
          totalAmount: order.totalAmount || order.totalPrice,
          unitPrice: order.unitPrice,
          orderNumber: order.orderNumber,
        };
        pay(paymentRequest)
          .then((res) => {
            uni.hideLoading();
            if (res.code === 200) {
              uni.showToast({ title: "支付成功", icon: "success" });
              // 清除本地该订单
              let unpaidOrders = uni.getStorageSync("unpaidOrders") || [];
              unpaidOrders = unpaidOrders.filter(
                (o) => o.orderNumber !== order.orderNumber
              );
              uni.setStorageSync("unpaidOrders", unpaidOrders);
              setTimeout(() => {
                uni.redirectTo({ url: "/pages/pay/payment-success" });
              }, 1500);
            } else {
              uni.showToast({ title: res.msg || "支付失败", icon: "none" });
            }
          })
          .catch(() => {
            uni.hideLoading();
            uni.showToast({ title: "支付异常", icon: "none" });
          });
      }
    },
  },
};
</script>

<style scoped>
.payment-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 60px;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 44px 16px 12px;
  background: #fff;
  z-index: 100;
}

.nav-left {
  width: 24px;
}

.back-icon {
  font-size: 24px;
  color: #333;
}

.nav-title {
  flex: 1;
  font-size: 18px;
  font-weight: 500;
  color: #333;
  text-align: center;
  margin-right: 24px;
}

.amount-section {
  margin-top: 72px;
  background: #fff;
  padding: 24px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.amount {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.countdown {
  font-size: 14px;
  color: #666;
}

.payment-methods {
  margin-top: 12px;
  background: #fff;
  padding: 16px;
}

.section-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 16px;
}

.method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.method-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.method-icon {
  width: 24px;
  height: 24px;
}

.method-name {
  font-size: 16px;
  color: #333;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background: #fff;
  border-top: 1px solid #eee;
}

.price-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.final-price {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.pay-btn {
  width: 35%;
  background: #ff4d4f;
  color: #fff;
  padding: 8px 24px;
  border-radius: 4px;
  font-size: 16px;
}
</style>